// 引入模块依赖
const fs = require('fs');
const path = require('path');
const jsonwebtoken = require('jsonwebtoken');//JSON Web令牌签名和验证
// const expressJwt = require('express-jwt');//JWT令牌的权限中间件
let cert_public = fs.readFileSync(path.join(__dirname, './pem/public_key.pem'));//公钥 可以自己生成
let cert_private = fs.readFileSync(path.join(__dirname, './pem/private_key.pem'));//私钥 可以自己生成
// 创建 token 类
class JwtUtil {
    //生成token
    generateToken(data) {
        return new Promise((resolve, reject) => {
            const expiresIn = 6000
            jsonwebtoken.sign(data, cert_private, {algorithm: 'RS256', expiresIn}, function (err, token) {
                resolve([err, token])
            });
        });
    }

    // 校验token
    verifyToken(token) {
        return new Promise((resolve, reject) => {
            jsonwebtoken.verify(token, cert_public, {algorithms: ['RS256']}, (err) => {
                if(!err){
                    resolve({status: 200, msg: "验证通过"});
                    return
                }
                switch (err.name) {
                    case 'TokenExpiredError'://token过期错误
                    case 'NotBeforeError'://当前时间超过nbf的值时抛出该错误
                        resolve({
                            status: 403,
                            msg: "token过期了"
                        })
                        break
                    case 'JsonWebTokenError'://令牌有问题
                        resolve({
                            status: 403,
                            msg: "token被篡改"
                        })
                        break;
                    default:
                        resolve({
                            status: 403,
                            msg: "token解析到未知错误"
                        })
                        break;
                }
            });
            let {exp = 0} = result, current = Math.floor(Date.now() / 1000);
            console.log(result, typeof exp, typeof current, current <= exp, current - exp)
            if (current <= exp) {
                res = result.data;
            }
        })
    }

}

module.exports = new JwtUtil();
